package com.effectiv.gooruda.rest.api.service;

import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.activemq.ScheduledMessage;
import org.springframework.jms.core.MessageCreator;


import com.effectiv.gooruda.rest.api.domain.CloudMessage;

@Slf4j
@AllArgsConstructor
public class DefaultMessageCreator implements MessageCreator {
	
	
	private CloudMessage message;
	
	private final long DEFAULT_EXPIRY = 604800L;
	private final long MAX_EXPIRY = 2592000L;
	private final long MAX_DELAY = 604800L;
	
	
	@Override
	public Message createMessage(Session session) throws JMSException {
		ObjectMessage m = session.createObjectMessage(message);
		m.setJMSCorrelationID(UUID.randomUUID().toString());
		
		long expiry = message.getExpiration();
		
		if(expiry <= 0){
			expiry = DEFAULT_EXPIRY;
		}
		
		else if(expiry > MAX_EXPIRY){
			expiry = MAX_EXPIRY;
		}
		
		
		
		log.info("######## EXPIRY IN SECONDS = {}", expiry);
		
		
		m.setJMSExpiration(expiry*1000);
		
		long delay = message.getDelay();
		
		if(delay > MAX_DELAY){
			delay = MAX_DELAY;
		}
		
		m.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay * 1000);
		
		return m;
	}

}
